package com.example.design.patterns.geekbang.创建型.工厂模式.DI框架.执行入口;

import com.example.design.patterns.geekbang.创建型.工厂模式.DI框架.核心工厂类.BeansFactory;
import com.example.design.patterns.geekbang.创建型.工厂模式.DI框架.配置解析.BeanConfigParser;
import com.example.design.patterns.geekbang.创建型.工厂模式.DI框架.配置解析.BeanDefinition;
import com.example.design.patterns.geekbang.创建型.工厂模式.DI框架.配置解析.XmlBeanConfigParser;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ClassPathXmlApplicationContext implements ApplicationContext {
    private BeansFactory beansFactory;
    private BeanConfigParser beanConfigParser;

    public ClassPathXmlApplicationContext(String configLocation) {
        this.beansFactory = new BeansFactory();
        this.beanConfigParser = new XmlBeanConfigParser();
        loadBeanDefinitions(configLocation);
    }

    private void loadBeanDefinitions(String configLocation) {
        try (InputStream in = this.getClass().getResourceAsStream("/" + configLocation)) {
            if (in == null) {
                throw new RuntimeException("Can not find config file: " + configLocation);
            }
            List<BeanDefinition> beanDefinitions = beanConfigParser.parse(in);
            beansFactory.addBeanDefinitions(beanDefinitions);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // TODO: log error
    }

    @Override
    public Object getBean(String beanId) {
        return beansFactory.getBean(beanId);
    }
}